﻿#include "systemsettingform.h"
#include "ui_systemsettingform.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include "clientcallback.h"
#include "confsettings.h"
#include "globaltools.h"
#include "uitools.h"
#include "usersettings.h"

SystemSettingForm* SystemSettingForm::showWindow()
{
    SystemSettingForm* window = instance();
    if(window->isHidden())
    {
        window->raise();
        window->showNormal();
    }
    return window;
}

SystemSettingForm::SystemSettingForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SystemSettingForm)
{
    setWindowFlags(Qt::Window);
    setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);
    QString ver = getCurrentVersion();
    if(ver.isEmpty())
        ui->label->hide();
    else
        ui->label->setText(QObject::trECSUTF8("版本信息: ") + ver);
    auto conf = ConfSettings::instance();
    ui->lineEdit_server->setPlaceholderText(conf->appDomain);
    auto settings = UserSettings::instance();
    ui->lineEdit_server->setText(settings->getString(UserSettings::sys_server_domain));
    showHost(conf);
    if(conf->mdsList.isEmpty())
        ui->label_mds->hide();
    else
        ui->label_mds->setText("MDS: " + conf->mdsList);
    ui->push_reset->setEnabled(!settings->getString(UserSettings::sys_server_domain).isEmpty() ||
                               !settings->getString(UserSettings::sys_server_proxy).isEmpty());
}

SystemSettingForm::~SystemSettingForm()
{
    delete ui;
}

void SystemSettingForm::showHost(const ConfSettings *conf)
{
    ui->label_web->setText(conf->validDomain);
    ui->label_login->setText(conf->validProxy);
}

void SystemSettingForm::slot_proxy_finished()
{
    auto reply = qobject_cast<QNetworkReply*>(sender());
    if(reply && reply->error() == QNetworkReply::NoError)
    {
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
        if(doc.isObject())
        {
            auto root = doc.object();
            if(root.value("success").toBool())
            {
                QString proxy = root.value("obj").toObject().value("ProxyServer").toString();
                if(!proxy.isEmpty())
                {
                    auto settings = UserSettings::instance();
                    auto conf = ConfSettings::instance();
                    auto oldProxy = conf->validProxy;
                    QString server = ui->lineEdit_server->text();
                    if(!server.isEmpty() && server != conf->validDomain)
                    {
                        auto settings = UserSettings::instance();
                        if(settings->setValueIfChanged(UserSettings::sys_server_domain, server))
                        {
                            settings->save_system_setting();
                            conf->updateDomain(server);
                        }
                    }
                    else if(proxy == conf->appProxy)
                    {
                        //默认domain，如果proxy也等于默认，设置就置空
                        proxy.clear();
                    }
                    if(settings)
                    {
                        if(settings->setValueIfChanged(UserSettings::sys_server_proxy, proxy))
                        {
                            settings->save_system_setting();
                            conf->updateProxy(server, proxy);
                            ClientCallback::instance()->set_pxy_servers(conf->validProxy);
                        }
                    }
                    else
                    {
                        conf->updateProxy(server, proxy);
                        ClientCallback::instance()->set_pxy_servers(conf->validProxy);
                    }
                    showHost(conf);
                    ui->push_server->setEnabled(true);
                    ui->push_reset->setEnabled(!settings->getString(UserSettings::sys_server_domain).isEmpty() ||
                                               !settings->getString(UserSettings::sys_server_proxy).isEmpty());
                    if(oldProxy != conf->validProxy)
                        emit proxyChanged();
                    information(QObject::trECSUTF8("更新成功"),QObject::trECSUTF8("更新登录服务器成功"), this);
                    return;
                }
            }
        }
    }
    information(QObject::trECSUTF8("获取失败"),QObject::trECSUTF8("获取登录服务器失败")+"!", this);
    ui->push_server->setEnabled(true);
}

void SystemSettingForm::on_push_disable_device_clicked()
{
    if(confirm(QObject::trECSUTF8("确认"), QObject::trECSUTF8("是否确认将音视频设备设为禁用?"), this))
    {
        bool changed  = false;
        auto settings = UserSettings::instance();
        if(settings->setValueIfChanged(UserSettings::sys_video_index, -1))
        {
            changed = true;
            ClientCallback::instance()->set_camera_id(-1);
        }
        if(settings->setValueIfChanged(UserSettings::sys_speaker_index, -1))
        {
            changed = true;
            ClientCallback::instance()->set_speaker_id(-1);
        }
        if(settings->setValueIfChanged(UserSettings::sys_mic_index, -1))
        {
            changed = true;
            ClientCallback::instance()->set_microphone_id(-1);
        }
        if(changed)
            settings->save_system_setting();
    }
}

void SystemSettingForm::on_push_disable_autoLogin_clicked()
{
    auto settings = UserSettings::instance();
    if(settings->setValueIfChanged(UserSettings::sys_auto_login, false))
    {
        settings->save_system_setting();
        information(QString(), QObject::trECSUTF8("自动登录已取消"), this);
    }
    else
        information(QString(), QObject::trECSUTF8("未设置自动登录"), this);
}

void SystemSettingForm::on_push_server_clicked()
{
    auto conf = ConfSettings::instance();
    QString server = ui->lineEdit_server->text();
    ui->push_server->setEnabled(false);
    if(server.isEmpty())
    {
        //使用默认，设置置空
        auto settings = UserSettings::instance();
        if(settings->setValueIfChanged(UserSettings::sys_server_domain, QVariant()))
        {
            //domain变化后，如果有原本存的proxy应该清除
            ui->push_reset->setEnabled(false);
            settings->setValueIfChanged(UserSettings::sys_server_proxy, QVariant());
            settings->save_system_setting();
            conf->updateDomain(QString());
            conf->updateProxy(QString(), QString());
            ClientCallback::instance()->set_pxy_servers(conf->validProxy);
        }
        ui->label_web->setText(conf->validDomain);
        //下载proxy
        getProxy(conf->validDomain, this, SLOT(slot_proxy_finished()));
        return;
    }
    //验证是否http开头
    if(server.startsWith("http://", Qt::CaseInsensitive) || server.startsWith("https://", Qt::CaseInsensitive))
    {
        server = QUrl(server.trimmed()).toString(QUrl::StripTrailingSlash | QUrl::NormalizePathSegments);
        //清除末尾的斜杠
        while (server.endsWith('/') || server.endsWith('\\'))
            server.chop(1);
        ui->lineEdit_server->setText(server);
        getProxy(server, this, SLOT(slot_proxy_finished()));
    }
    else
        information(QString(), QObject::trECSUTF8("服务器格式不正确"), this);
}

void SystemSettingForm::on_push_reset_clicked()
{
    //重置与更新时输入框留空的区别：1.重置不管原来domain是不是默认都清空proxy 2.重置时不下载服务器信息
    if(question(QObject::trECSUTF8("确认"), QObject::trECSUTF8("是否确认重置服务器信息?"), this))
    {
        ui->push_reset->setEnabled(false);
        auto settings = UserSettings::instance();
        bool changed = settings->setValueIfChanged(UserSettings::sys_server_domain, QVariant());
        changed = settings->setValueIfChanged(UserSettings::sys_server_proxy, QVariant()) || changed;
        if(changed)
            settings->save_system_setting();
        auto conf = ConfSettings::instance();
        auto oldProxy = conf->validProxy;
        conf->updateDomain(QString());
        conf->updateProxy(QString(), QString());
        ClientCallback::instance()->set_pxy_servers(conf->validProxy);
        showHost(conf);
        ui->lineEdit_server->clear();
        if(oldProxy != conf->validProxy)
            emit proxyChanged();
    }
}
